package com.jlanglang.glide.loaderdemo.loader

import com.bumptech.glide.Priority
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.data.DataFetcher
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.signature.ObjectKey
import com.jlanglang.glide.loaderdemo.fetcher.JHttpUrlFetcher
import com.jlanglang.glide.loaderdemo.util.DESUtil
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.net.URL
import java.security.MessageDigest

/**
 * 随便取的名字
 * @author Jlanglang
 */
class UrlModelLoader : ModelLoader<UrlModel, InputStream> {
    override fun handles(model: UrlModel): Boolean {
        return true
    }

    override fun buildLoadData(
        model: UrlModel,
        width: Int,
        height: Int,
        options: Options
    ): ModelLoader.LoadData<InputStream>? {
        //创建loadData,DESHttpUrlFetcher是用Glide自带的HttpUrlFetcher改造了一下
        val httpUrlFetcher = object : JHttpUrlFetcher(model.url, 2500) {
            override fun loadDataWithRedirects(
                url: URL?, redirects: Int, lastUrl: URL?,
                headers: MutableMap<String, String>?
            ): InputStream? {
                //这里返回网络请求的InputStream
                val inputStream = super.loadDataWithRedirects(url, redirects, lastUrl, headers)
                //加密
                val readBytes = inputStream.readBytes();
                val encode = DESUtil.encode(readBytes, "12345678")
                //如果需要解密
                if (url.toString() != "") {
                    //做解密操作
                    return DESUtil.decodeInputStream(ByteArrayInputStream(encode), "12345678")
                }
                return ByteArrayInputStream(encode)
            }
        }
        return ModelLoader.LoadData(model, httpUrlFetcher)
    }
}


/**
 * 自定义的类,作为识别的关键
 */
class UrlModel(var url: String) : Key {
    private val cacheKeyBytes = url.toByteArray()
    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(cacheKeyBytes)
    }
}